package com.longma.server.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.longma.server.dao.SysUserDAO;
import com.longma.server.constant.enums.ResponseCode;
import com.longma.server.entity.SysUser;
import com.longma.server.exception.BusinessException;
import com.longma.server.security.JwtUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

/**
 * @author HIBO
 * @Description 自定义用户登录认证逻辑
 */


@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserDAO sysUserDAO;

    /**
     * 加载用户信息  并校验用户合法性，失败抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String loginName){
        //参数校验
        if (StrUtil.isBlank(loginName)){
            throw new BusinessException(ResponseCode.USER_ACCOUNT_NOT_EXIST);
        }

        SysUser loginUser = sysUserDAO.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getLoginName,loginName));
        if (loginUser == null) {
            throw new BusinessException(ResponseCode.USER_ACCOUNT_NOT_EXIST);
        }

        JwtUserDetails jwtUserDetails = new JwtUserDetails(loginUser);

        return new User(
                jwtUserDetails.getUsername(),
                jwtUserDetails.getPassword(),
                jwtUserDetails.isEnabled(),
                jwtUserDetails.isAccountNonExpired(),
                jwtUserDetails.isCredentialsNonExpired(),
                jwtUserDetails.isAccountNonLocked(),
                jwtUserDetails.getAuthorities()
        );
    }
}
